import axios from 'axios'
import { throttleRedirectLogin } from './util'
import { Token } from '@/lib/token'

axios.defaults.timeout = 10000
axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'

axios.interceptors.request.use(
  config => {
    // 标示请求为xhr请求
    // config.headers.common['X-Requested-With'] = 'XMLHttpRequest'
    const token = Token.get()
    if (token) {
      config.headers.common.token = token
    }
    // Remove Content-Type if data is undefined
    // axios 会删除get请求中headers Content-Type 为了令axios不删除，随便设置一个值给data
    if (config.method === 'get') {
      config.data = true
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(
  response => {
    if (response.data) {

    }
    return response
  },
  err => {
    if (err && err.code) {
      if (err.code === 'ECONNABORTED') {
        err.message = '请求超时'
      }
    }
    if (err && err.response) {
      const status = err.response.status
      const errorMessage =
        err.response?.data?.data?.message ||
        err.response?.data?.message
      switch (status) {
        case 400:
          err.message = errorMessage
          break

        case 401:
          err.message = errorMessage
          throttleRedirectLogin(err.response.data)
          break

        case 403:
          err.message = errorMessage
          break

        case 404:
          err.message = errorMessage || `请求地址出错: ${err.response.config.url}`
          break

        case 408:
          err.message = errorMessage || '请求超时'
          break

        case 500:
          err.message = errorMessage || '服务器内部错误'
          break

        case 501:
          err.message = errorMessage || '服务未实现'
          break

        case 502:
          err.message = errorMessage || '网关错误'
          break

        case 503:
          err.message = errorMessage || '服务不可用'
          break

        case 504:
          err.message = errorMessage || '网关超时'
          break

        case 505:
          err.message = errorMessage || 'HTTP版本不受支持'
          break

        default:
      }
    }
    return Promise.reject(err)
  })

export { UploadFile } from './upload-file'
export { DownloadFile } from './download-file'
export { request } from './basic-request'
